﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using PMS.EntityQuery;
using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using EntityManage;

/// <summary>
/// Summary description for FlowTrace
/// </summary>
public class FlowTrace
{
    public FlowTrace()
    {
    }

    public static void ProcessFlowTraceStep(string[] traceIds, string comment, int isPast,
        Sys_UserQuery userQuery, HttpFileCollection files, ref bool isLastStep)
    {
        IPerf_Flow_TraceHandler traceHandler = new Perf_Flow_TraceManage();
        IPerf_FlowHandler flowHandler = new Perf_FlowManage();
        IPerf_Flow_StepsHandler stepsHandler = new Perf_Flow_StepsManage();
        ISys_UserHandler userHandler = new Sys_UserManage();
        IPerf_Flow_TraceDtlHandler traceDtlHandler = new Perf_Flow_TraceDtlManage();
        IPerf_Flow_TraceAttachHandler traceAttachHandler = new Perf_Flow_TraceAttachManage();

        foreach (string tmpid in traceIds)
        {
            // 判断状态
            int ttid = int.Parse(tmpid);
            Perf_Flow_TraceQuery traceQuery = traceHandler.GetPerf_Flow_TraceQuery(ttid);
            if (traceQuery != null && traceQuery.Status == (int)Enums.FlowTraceStatus.OnGoing)
            {
                // 读取流程配置信息
                Perf_FlowQuery flowQuery = flowHandler.GetPerf_FlowQuery(traceQuery.Flow_ID);
                Perf_Flow_StepsQuery[] steps = stepsHandler.GetPerf_Flow_StepsQueryList(" Flow_ID = @Flow_ID and IsEnable = 1",
                    new SqlParameter[] { new SqlParameter("@Flow_ID", flowQuery.ID) }, " Step_Num asc ");

                isLastStep = false;
                Perf_Flow_StepsQuery currentStepQuery = null;
                if (traceQuery.Current_Step == 0)
                {
                    currentStepQuery = steps[0];
                    if (steps.Length == 1)
                        isLastStep = true;
                }
                else
                {
                    Perf_Flow_StepsQuery lastStepQuery = stepsHandler.GetPerf_Flow_StepsQuery(traceQuery.Current_Step_ID);
                    for (int i = 0; i < steps.Length; i++)
                    {
                        Perf_Flow_StepsQuery tmpStep = steps[i];
                        if (tmpStep.ID == lastStepQuery.ID)
                        {
                           
                            if (traceQuery.Flow_ID == 3000)//申诉流程
                            {


                                if (steps.Length - 1 == i)
                                {
                                    currentStepQuery = steps[i];
                                    isLastStep = true;
                                }
                                else
                                {
                                    currentStepQuery = steps[i+1];
                                }
                            }
                            else
                            {
                                currentStepQuery = steps[i + 1];

                                if (steps.Length - 2 == i)
                                {
                                    isLastStep = true;
                                }
                            }

                            break;
                        }
                    }
                }

                // 添加到跟踪子表
                Perf_Flow_TraceDtlQuery traceDtlQuery = new Perf_Flow_TraceDtlQuery();
                traceDtlQuery.Flow_Trace_ID = traceQuery.ID;
                traceDtlQuery.Step_ID = currentStepQuery.ID;
                traceDtlQuery.User_ID = userQuery.ID;
                traceDtlQuery.Flow_Time = DateTime.Now;
                traceDtlQuery.Comment = comment;
                traceDtlQuery.Is_Past = isPast;

                int traceDtlId = 0;
                traceDtlHandler.InsertPerf_Flow_TraceDtl(traceDtlQuery, ref traceDtlId);

                // 添加附件
                if (files != null && files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile postedFile = files[i];
                        string fileName, fileExtension;
                        fileName = System.IO.Path.GetFileName(postedFile.FileName);
                        if (fileName != "")
                        {
                            fileExtension = System.IO.Path.GetExtension(fileName);
                            string path = System.Web.HttpContext.Current.Request.MapPath("~");
                            path = path + "/" + Enums.Flow_Trace_Attach_Path + traceDtlId.ToString();
                            if (!Directory.Exists(path))
                                Directory.CreateDirectory(path);
                            postedFile.SaveAs(path + "/" + fileName);
                        }

                        Perf_Flow_TraceAttachQuery attchQuery = new Perf_Flow_TraceAttachQuery();
                        attchQuery.Flow_TraceDtl_ID = traceDtlId;
                        attchQuery.User_ID = userQuery.ID;
                        attchQuery.Name = fileName;
                        attchQuery.Size = postedFile.ContentLength;
                        attchQuery.Path = Enums.Flow_Trace_Attach_Path + traceDtlId.ToString() + "/" + fileName;
                        traceAttachHandler.InsertPerf_Flow_TraceAttach(attchQuery);
                    }
                }

                // 更新流程跟踪主表
                traceQuery.Current_Step = currentStepQuery.Step_Num;
                traceQuery.Current_Step_ID = currentStepQuery.ID;
                traceQuery.Is_Past = traceDtlQuery.Is_Past;
                if (traceDtlQuery.Is_Past == 1 || isLastStep == true)
                {
                    traceQuery.Status = (int)Enums.FlowTraceStatus.Finished;
                    traceQuery.End_Time = DateTime.Now;
                }
                else
                {
                    traceQuery.Status = (int)Enums.FlowTraceStatus.OnGoing;
                }
                traceHandler.UpdatePerf_Flow_Trace(traceQuery);

            }
        }
    }


    public static string GetUserCurrentFlowBusinessIds(int userId, int flowId)
    {
        ISys_UserHandler userHandler = new Sys_UserManage();
        IPerf_FlowHandler flowHandler = new Perf_FlowManage();
        IPerf_Flow_StepsHandler fstepHandler = new Perf_Flow_StepsManage();
        IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();

        Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(userId);

        Perf_FlowQuery pfaQuery = flowHandler.GetPerf_FlowQuery(flowId);
        string whereSql = BusinessManage.GetFlowStepsSql(pfaQuery.ID, 1, userQuery);
        SqlParameter[] parms2 = new SqlParameter[] { };
        Perf_Flow_StepsQuery[] stepList = fstepHandler.GetPerf_Flow_StepsQueryList(whereSql, parms2, " Step_Num asc");

        StringBuilder myStepIds = new StringBuilder();
        bool hasFirstStepID = false;
        if (stepList != null && stepList.Length > 0)
        {
            foreach (Perf_Flow_StepsQuery stepQuery in stepList)
            {
                myStepIds.Append(stepQuery.ID);
                myStepIds.Append(",");
                if (stepQuery.Step_Num == 1 && stepQuery.Prev_ID == 0)
                    hasFirstStepID = true;
            }
            myStepIds = myStepIds.Remove(myStepIds.Length - 1, 1);
        }

        whereSql = " Status = @Status and Flow_ID = @Flow_ID and ((Current_Step = 0 and " + (hasFirstStepID ? "1=1" : "1!=1") + ") or Current_Step_ID in (" + myStepIds.ToString() + "))";
        parms2 = new SqlParameter[] { new SqlParameter("@Status", (int)Enums.FlowTraceStatus.OnGoing), new SqlParameter("@Flow_ID", pfaQuery.ID) };
        DataTable dtFlowTrace = flowTraceHandler.GetPerf_Flow_TraceList(whereSql, parms2);
        StringBuilder businessIds = new StringBuilder();
        if (dtFlowTrace != null && dtFlowTrace.Rows.Count > 0)
        {
            foreach (DataRow dr in dtFlowTrace.Rows)
            {
                businessIds.Append(dr["Business_ID"].ToString());
                businessIds.Append(",");
            }
            businessIds = businessIds.Remove(businessIds.Length - 1, 1);
        }

        return businessIds.ToString();
    }
}
